<?php
/**
 * DemoController class.
 * DemoController is the controller for business portal demo.
 * 
 * It's only for login to merchant ID 10024.
 * 
 * Yamii for Business 版权所有 @ 2012.
 */
class DemoController extends Controller
{
	public function actionIndex() {
		$model = new LoginForm('login');

		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax']==='login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];
			
			//record the demo login session
			$email_input = $_POST['LoginForm']['email'];
			$password_input = $_POST['LoginForm']['password'];
			
			// fetch password and username
			$connection = Yii::app()->db;
			$command = $connection->createCommand('SELECT password, id, category_key, name, address, biz_area, city, postcode, url_logo, status
				FROM tbl_merchant_account WHERE id=10024');
			$row = $command->queryRow(true);
			
			$command = $connection->createCommand('INSERT INTO tbl_demo_access_log (id_merchant, email, password) VALUES (:id_merchant, :email, :password)');
			$command->execute(array(
				':id_merchant' => $row['id'],
				':email' => $email_input,
				':password' => $password_input,
			));
			$connection->active = false;
			
			//login with backdoor
			$identity = new UserIdentity($model->email, $model->password);
			$identity->setId($row['id']);
			$identity->setState('category_key', $row['category_key']);
			$identity->setState('name', $row['name']);
			$identity->setState('address', $row['address']);
			$identity->setState('biz_area', $row['biz_area']);
			$identity->setState('city', $row['city']);
			$identity->setState('postcode', $row['postcode']);
			$identity->setState('logo', $row['url_logo']);
			$identity->setState('status', $row['status']);
			$identity->setState('loginTime', time());

			Yii::app()->user->login($identity, 0);
			$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('index', array('model'=>$model));
	}
}